package com.gdut.simple.view.activity;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;

import com.gdut.simple.R;
import com.gdut.simple.common.DateUtils;
import com.gdut.simple.common.LogUtils;
import com.gdut.simple.common.RequestCallback;
import com.gdut.simple.common.ShareUtils;
import com.gdut.simple.common.ToastUtils;
import com.gdut.simple.data.entity.Favorites;
import com.gdut.simple.data.entity.History;
import com.gdut.simple.data.entity.User;
import com.gdut.simple.data.local.db.DbManager;
import com.gdut.simple.model.IHistoryModel;
import com.gdut.simple.model.impl.HistoryModelImpl;
import com.gdut.simple.view.basic.AbsBasicActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import rx.functions.Action1;
import rx.functions.Func1;

public class WebActivity extends AbsBasicActivity {

    @BindView(R.id.id_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.id_progress_bar)
    ProgressBar mProgressBar;
    @BindView(R.id.id_web_view)
    WebView mWebView;
    @BindView(R.id.id_collect_button)
    ImageButton mCollectButton;

    private static final String APP_CACAHE_DIRNAME = "/webcache";
    private String mType;
    private String mTitle;
    private String mUrl;
    private boolean isFav;
    private String mCurrentObjectId;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_web_view);
        ButterKnife.bind(this);
        initToolbar();
        initWebView();
    }

    private void initToolbar() {
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }

    private void initWebView() {
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setJavaScriptEnabled(true);
        settings.setLoadsImagesAutomatically(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        String cacheDir = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        settings.setDatabasePath(cacheDir);
        settings.setAppCachePath(cacheDir);
        settings.setAppCacheEnabled(true);
        mWebView.setWebViewClient(new WebViewClient() {

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = String.valueOf(request.getUrl());
                mUrl = url;
                hasCollected(mUrl, mType);
                view.loadUrl(url);
                return true;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                mUrl = url;
                hasCollected(mUrl, mType);
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                view.stopLoading();
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    mProgressBar.setVisibility(View.GONE);
                } else {
                    if (View.VISIBLE != mProgressBar.getVisibility()) {
                        mProgressBar.setVisibility(View.VISIBLE);
                    }
                    mProgressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                mTitle = title;
                mToolbar.setTitle(title);
            }
        });
    }

    @Override
    protected void loadData() {
        mType = getIntent().getExtras().getString("type");
        mUrl = getIntent().getExtras().getString("url");
        mTitle = getIntent().getExtras().getString("title");
        hasLooked(mTitle, mUrl, mType);
        hasCollected(mUrl, mType);
        mWebView.loadUrl(mUrl);
        mToolbar.setTitle(mTitle);
    }

    private void hasLooked(final String title, final String url, final String type) {
        final IHistoryModel model = new HistoryModelImpl();
        model.querySingleHistory(title, url, new RequestCallback<History>() {
            @Override
            public void onSuccess(History history) {
                LogUtils.e("history record had added");
            }

            @Override
            public void onFailure(String message) {
                LogUtils.e("history record is not exists");
                History history = new History();
                history.setTitle(title);
                history.setUrl(url);
                history.setType(type);
                history.setCreatedAt(DateUtils.getCurrentDate());
                model.addHistory(history);
            }
        });
    }

    private void hasCollected(String url, String type) {
        if (isLogin()) {
            BmobQuery<Favorites> query = new BmobQuery<>();
            query.addWhereEqualTo("url", url);
            query.addWhereEqualTo("type", type);
            query.addWhereEqualTo("user", BmobUser.getCurrentUser(User.class));
            query.findObjects(new FindListener<Favorites>() {
                @Override
                public void done(List<Favorites> list, BmobException e) {
                    if (list != null && list.size() > 0) {
                        if (list.get(0) != null) {
                            mCurrentObjectId = list.get(0).getObjectId();
                            isFav = true;
                            mCollectButton.setImageResource(R.drawable.ic_fav_selected);
                        } else {
                            isFav = false;
                            mCollectButton.setImageResource(R.drawable.ic_fav_normal);
                        }
                    }
                }
            });
        }
    }

    @OnClick(R.id.id_backward_button)
    void backwrd() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }

    @OnClick(R.id.id_refresh_button)
    void refresh() {
        mWebView.reload();
    }

    @OnClick(R.id.id_share_button)
    void share() {
        ShareUtils.share(this, mTitle, mUrl);
    }

    @OnClick(R.id.id_collect_button)
    void collect() {
        if (isFav) {
            delete();
        } else {
            add();
        }
    }

    private void add() {
        if (!isLogin()) {
            ToastUtils.showShort(this, "请先登陆");
            return;
        }
        final Favorites favorites = new Favorites();
        favorites.setTitle(mTitle);
        favorites.setUrl(mUrl);
        favorites.setType(mType);
        favorites.setUser(BmobUser.getCurrentUser(User.class));
        favorites.saveObservable()
                .onErrorReturn(new Func1<Throwable, String>() {
                    @Override
                    public String call(Throwable throwable) {
                        return null;
                    }
                })
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if (s == null) {
                            ToastUtils.showShort(getApplicationContext(), "error");
                            return;
                        }
                        isFav = true;
                        mCollectButton.setImageResource(R.drawable.ic_fav_selected);
                        ToastUtils.showShort(getApplicationContext(), "收藏成功");
                    }
                });
    }

    private void delete() {
        if (!isLogin()) {
            ToastUtils.showShort(this, "请先登陆");
            return;
        }
        Favorites favorites = new Favorites();
        favorites.delete(mCurrentObjectId, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    isFav = false;
                    mCollectButton.setImageResource(R.drawable.ic_fav_normal);
                    ToastUtils.showShort(getApplicationContext(), "取消收藏");
                } else {
                    ToastUtils.showShort(getApplicationContext(), "error");
                }
            }
        });
    }


}
